/****************************************************
          File Name:52-4-client.c
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 21 Sep 2014 04:45:31 PM CST
*****************************************************/

#include"mq.h"
#include<pthread.h>

void *tfun(void *arg)
{
	mqd_t tar_client;
	char *para=(char *)arg;
	char *buf;
	struct mq_attr attr;
	int status;
	
	tar_client=mq_open(para,O_RDWR);
	if(tar_client==(mqd_t)-1)
		err("open target client");
	if(mq_getattr(tar_client,&attr)==-1)
		err("getattr");
	buf=malloc(attr.mq_msgsize);
	if(buf==NULL)
		err("malloc");
	for(;;)
	{
		status=mq_receive(tar_client,buf,attr.mq_msgsize,0);
		if(status==0)
			break;
		if(status==-1)
			err("mq_receive");
		
		printf("\e[36mreceived message:\e[0m\n%s",buf);
		if(memset(buf,0,attr.mq_msgsize)==NULL)
			err("clean buf");
		printf("\e[32mInput your message('ctrl+d' to exit 'Enter' to receive message[if message exist]):\e[0m\n");
	}
	
	return (void *)NULL;
}	

int main(int argc,char *argv[])
{
    if(argc<2 || strcmp(argv[1],"--help")==0)
    {
        printf("%s /ownmq /client\n",argv[0]);
        exit(EXIT_FAILURE);
    }

    mqd_t server, client,tar_client;
    struct mq_attr attr;
    char *re_buf, *se_buf; /* receive data buf & send data buf */
    pthread_t tid;			/* thread receive message */
    int res;

    server=mq_open(SERVER,O_RDWR);
    if(server==(mqd_t)-1)
        err("open server");
    client=mq_open(argv[1],O_RDWR);
    if(client==(mqd_t)-1)
        err("client create");
    if(mq_getattr(client,&attr)==-1)
        err("getattr");
    se_buf=malloc(attr.mq_msgsize);
    if(se_buf==NULL)
        err("malloc");
    re_buf=malloc(attr.mq_msgsize);
    if(re_buf==NULL)
        err("malloc");
    if(mq_send(server,argv[1],strlen(argv[1]),0)==-1) /* send server self id */
        err("send client id to server");

	tar_client=mq_open(argv[2],O_RDWR);
	if(tar_client==(mqd_t)-1)
		err("open target client");

        if(mq_send(server,argv[2],10,0)==-1) /* send server target id "/client"*/
            err("send target to server");
   
		
	res=pthread_create(&tid,NULL,tfun,argv[2]);
		if(res!=0)
			err("pthread_create");
		
		
		printf("************* start senssion ***************\n");
		printf("\e[32mInput your message('ctrl+d' to exit 'Enter' to receive message[if message exist]):\e[0m\n");
        
	for(;;)
	{
		if(fgets(se_buf,attr.mq_msgsize,stdin)==NULL)
			if(se_buf[0]=='\0')
			{
            /* EOF is the terminate signal, when server receive 0 then exit */
				if(mq_send(client,se_buf,0,0)==-1)
					err("send terminate signal to server failed");
				break;
			}
		if(se_buf[0]!='\n')
			if(mq_send(client,se_buf,strlen(se_buf),0)==-1)
				err("can not send message");

		if(memset(se_buf,0,attr.mq_msgsize)==NULL)
			err("clean message");
	}
        
    printf("************* end senssion ***************\n");
	if(pthread_join(tid,NULL)!=0)
		err("wait thread exit");
	exit(EXIT_SUCCESS);
}
